#include "ir_remote.h"
#include <IRremoteESP8266.h>
#include <IRrecv.h>
#include <IRutils.h>

// 红外接收器实例
IRrecv irReceiver(IR_RECEIVE_PIN);

// 红外遥控实现
IRRemote::IRRemote() : lastCommand(0), lastReceiveTime(0) {
}

IRRemote::~IRRemote() {
}

void IRRemote::begin() {
    // 初始化红外接收器
    irReceiver.enableIRIn();
}

bool IRRemote::available() {
    decode_results results;
    
    // 检查是否接收到红外信号
    if (irReceiver.decode(&results)) {
        // 检查是否是重复按键
        unsigned long currentTime = millis();
        if (results.value == lastCommand && 
            (currentTime - lastReceiveTime) < REPEAT_SUPPRESS_TIME) {
            // 抑制重复按键
            irReceiver.resume();
            return false;
        }
        
        // 保存命令和时间
        lastCommand = results.value;
        lastReceiveTime = currentTime;
        
        // 准备接收下一个命令
        irReceiver.resume();
        
        return true;
    }
    
    return false;
}

uint32_t IRRemote::readCommand() {
    return lastCommand;
}

const char* IRRemote::getCommandName(uint32_t command) {
    switch (command) {
        case IR_CMD_POWER:
            return "POWER";
        case IR_CMD_MODE:
            return "MODE";
        case IR_CMD_NEXT:
            return "NEXT";
        case IR_CMD_PREVIOUS:
            return "PREVIOUS";
        case IR_CMD_PLAY:
            return "PLAY/PAUSE";
        case IR_CMD_UP:
            return "UP";
        case IR_CMD_DOWN:
            return "DOWN";
        case IR_CMD_LEFT:
            return "LEFT";
        case IR_CMD_RIGHT:
            return "RIGHT";
        case IR_CMD_ENTER:
            return "ENTER";
        default:
            return "UNKNOWN";
    }
}